package com.letou.ls.ui;

import org.apache.table.JsonUtil;
import org.apache.table.PreferencesUtils;

import com.letou.ls.R;
import com.letou.ls.mode.UserInfo;
import com.letou.ls.uitl.Constant;
import com.letou.ls.uitl.DialogUtils;
import com.letou.ls.uitl.Logger;
import com.letou.ls.uitl.MyUtil;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;

public class LoginActivity extends Activity implements OnClickListener {
    public static final String LAST_LOGIN_STATE = "login_state";

    private Button mButton;
    private FinalHttp fh = null;
    private ProgressDialog mProgressDialog;
    private EditText mNameEdit;
    private EditText mPassEdit;

    private boolean isSend = false;

    private boolean isLastSucceed;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        isLastSucceed = PreferencesUtils.getBoolean(this, LAST_LOGIN_STATE);

        View content = View.inflate(this, R.layout.activity_login, null);

        if (!isLastSucceed) setContentView(content);

        mNameEdit = (EditText) content.findViewById(R.id.Login_name);
        mPassEdit = (EditText) content.findViewById(R.id.Login_password);
        mButton = (Button) content.findViewById(R.id.login_button);
        mButton.setOnClickListener(this);
        name = PreferencesUtils.getString(this, Constant.PRE_TAG_USERNAME);
        password = PreferencesUtils.getString(this, Constant.PRE_TAG_PASSWROD);

        if (!TextUtils.isEmpty(name)) {
            mNameEdit.setText(name);
        }
        // mNameEdit.setText("lisong");
        // mPassEdit.setText("123");
        mProgressDialog = new ProgressDialog(this);
        mProgressDialog.setMessage("数据加载中请稍候...");

    }

    @Override
    protected void onStart() {
        // TODO Auto-generated method stub
        super.onStart();
        if (TextUtils.isEmpty(name) || TextUtils.isEmpty(password)) {
            return;
        }
        mNameEdit.setText(name);
        mPassEdit.setText(password);
        loadData();
    }

    @Override
    public void onClick(View arg0) {
        // TODO Auto-generated method stub
        loadData();
    }

    // 根据Wifi信息获取本地Mac
    public static String getLocalMacAddressFromWifiInfo(Context context) {
        
        // process has android.permission.ACCESS_WIFI_STATE.
        // <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"
        // />
        WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        WifiInfo info = wifi.getConnectionInfo();
        return info.getMacAddress();
    }

    private String name;
    private String password;

    public void loadData() {
        
        if (TextUtils.isEmpty(mNameEdit.getText()) || TextUtils.isEmpty(mPassEdit.getText())) {
            showDailog("用户名或密码不能为空！");
            return;
        }
        name = mNameEdit.getText().toString().replaceAll(" ", "");
        password = mPassEdit.getText().toString().replaceAll(" ", "");
        if (TextUtils.isEmpty(name) || TextUtils.isEmpty(password)) {
            showDailog("用户名或密码不能为空！");
            return;
        }
        if (isSend) {
            return;
        }
        isSend = true;
        mProgressDialog.show();
        // 网络连接类
        fh = new FinalHttp();
        String mac = getLocalMacAddressFromWifiInfo(this);
        // mac = "84:38:38:20:D8:42";

        String url = Constant.URL_SERVER_LOGIN + "?username=" + name + "&password=" + password
                + "&mac=" + mac + "";
        Logger.v("lss", url);
        // 获取IMEI
        fh.configTimeout(30000);
        fh.get(url, new AjaxCallBack<String>() {
            @Override
            public void onSuccess(String strJson) {
                
                // Logger.v("lss", "strJson " + strJson);
                // 登陆结果转换
                UserInfo userInfo = JsonUtil.fromJson(strJson, UserInfo.class);
                Constant.token = userInfo.getToken();
                // ArrayList<LotteryTypeInfo> list = new
                // ArrayList<LotteryTypeInfo>();
                // list.add(userInfo.getLotteryTypeInfo().get(0));

                // Constant.lotteryTypeInfo = list;
                Constant.lotteryTypeInfo = userInfo.getLotteryTypeInfo();
                Logger.v("lss", userInfo.toString());
                // 登陆成功
                boolean isLoginSuccess = "200".equals(userInfo.getCode());
                if (isLoginSuccess) {
                    
                    if (mProgressDialog.isShowing()) {
                        mProgressDialog.dismiss();
                    }
                    savePassword();
                    String lotteryCode = PreferencesUtils.getString(LoginActivity.this,
                            Constant.PRE_TAG_CURRENT_LTTERY_CODE);

                    if (!TextUtils.isEmpty(lotteryCode)) {
                        int size = Constant.lotteryTypeInfo.size();
                        for (int index = 0; index < size; index++) {
                            if (lotteryCode
                                    .equals(Constant.lotteryTypeInfo.get(index).getTypeCode())) {
                                Constant.currentLotteryNumber = index;
                                break;
                            }
                        }
                    }
                    Intent intent = MyUtil.getIntentById(LoginActivity.this, lotteryCode);
                    if (intent == null) {
                        intent = new Intent(LoginActivity.this, SelectActivity.class);
                    }
                    startActivity(intent);
                    finish();

                    // 登陆失败
                } else {
                    // failureProcess(userInfo.getMessage());
                    showDailog(MyUtil.getErrByCode(userInfo.getCode()));
                }
                PreferencesUtils.putBoolean(LoginActivity.this, LAST_LOGIN_STATE, isLoginSuccess);
                isSend = false;
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                // TODO
                showDailog("网络超时");
                isSend = false;
            }

        });
    }

    private void savePassword() {
        PreferencesUtils.putString(this, Constant.PRE_TAG_USERNAME, name);
        PreferencesUtils.putString(this, Constant.PRE_TAG_PASSWROD, password);
        Constant.userName = name;
    }

    private void showDailog(String message) {
        if (mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
        }
        DialogUtils.showDialog(LoginActivity.this, "提示", message);
    }
}
